<template>
  <div class="disease-page">
    <cp-nav-bar title="疾病详情" @click-right="onShare">
      <template #right><cp-icon name="share" /></template>
    </cp-nav-bar>

    <!-- 搜索框 -->
    <div class="search-section">
      <van-search
        v-model="searchKeyword"
        placeholder="搜索疾病信息..."
        show-action
        @search="onSearch"
        @clear="onClearSearch"
      >
        <template #action>
          <div @click="onSearch">搜索</div>
        </template>
      </van-search>
    </div>

    <!-- 搜索结果 -->
    <div v-if="searchResults.length > 0" class="search-results">
      <div class="result-header">
        <span>找到 {{ searchResults.length }} 个相关疾病</span>
        <van-button type="primary" size="mini" @click="clearSearchResults">
          清除结果
        </van-button>
      </div>
      <div
        class="result-item"
        v-for="result in searchResults"
        :key="result.id"
        @click="goToDisease(result.id)"
      >
        <div class="result-name">{{ result.name }}</div>
        <div class="result-summary">{{ result.summary || '暂无简介' }}</div>
        <div class="result-highlight" v-if="result.matchedContent">
          <span class="label">匹配内容：</span>
          <span v-html="result.matchedContent"></span>
        </div>
      </div>
    </div>

    <div v-if="!loading && disease" class="disease-detail">
      <!-- 疾病基本信息 -->
      <div class="disease-header">
        <div class="disease-info">
          <img
            :src="getDiseaseImage(disease.image_name)"
            class="disease-image"
            @error="onImageError"
          />
          <div class="info-content">
            <h1 class="disease-name">{{ disease.name }}</h1>
            <p class="english-name" v-if="disease.english_name">
              {{ disease.english_name }}
            </p>
            <div class="tags">
              <span class="special-tag" v-if="disease.is_special_zone === '是'">
                专科疾病
              </span>
              <span
                class="department-tag"
                v-for="dept in disease.departments"
                :key="dept.id"
                @click="onDepartmentClick(dept)"
              >
                {{ dept.name }}
              </span>
              <span class="update-time" v-if="disease.update_time">
                更新时间：{{ formatDate(disease.update_time) }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 疾病概述 -->
      <div class="detail-card" v-if="disease.summary">
        <h3>疾病概述</h3>
        <p>{{ disease.summary }}</p>
      </div>

      <!-- 症状表现 -->
      <div class="detail-card" v-if="disease.symptoms">
        <h3>症状表现</h3>
        <div class="content-with-icon">
          <van-icon name="warning-o" class="section-icon" />
          <p>{{ disease.symptoms }}</p>
        </div>
      </div>

      <!-- 病因分析 -->
      <div class="detail-card" v-if="disease.causes">
        <h3>病因分析</h3>
        <div class="content-with-icon">
          <van-icon name="question-o" class="section-icon" />
          <p>{{ disease.causes }}</p>
        </div>
      </div>

      <!-- 治疗方法 -->
      <div class="detail-card" v-if="disease.treatment">
        <h3>治疗方法</h3>
        <div class="content-with-icon">
          <van-icon name="plus" class="section-icon" />
          <p>{{ disease.treatment }}</p>
        </div>
      </div>

      <!-- 预防措施 -->
      <div class="detail-card" v-if="disease.prevention">
        <h3>预防措施</h3>
        <div class="content-with-icon">
          <van-icon name="shield-o" class="section-icon" />
          <p>{{ disease.prevention }}</p>
        </div>
      </div>

      <!-- 医疗建议 -->
      <div class="detail-card" v-if="disease.medical_advice">
        <h3>医疗建议</h3>
        <div class="content-with-icon">
          <van-icon name="service-o" class="section-icon" />
          <p>{{ disease.medical_advice }}</p>
        </div>
      </div>

      <!-- 日常护理 -->
      <div class="detail-card" v-if="disease.daily_care">
        <h3>日常护理</h3>
        <div class="content-with-icon">
          <van-icon name="like-o" class="section-icon" />
          <p>{{ disease.daily_care }}</p>
        </div>
      </div>

      <!-- 相关医生推荐 -->
      <div class="detail-card">
        <h3>相关医生推荐</h3>
        <div class="doctor-recommend">
          <van-button
            type="primary"
            size="large"
            round
            @click="onFindDoctor"
            icon="search"
          >
            查找相关医生
          </van-button>
        </div>
      </div>
    </div>

    <!-- Loading State -->
    <div v-else-if="loading" class="loading">
      <van-skeleton title avatar :row="5" />
    </div>

    <!-- 底部操作按钮 -->
    <div class="bottom-actions">
      <van-button
        type="default"
        size="large"
        @click="onAddToFavorites"
        icon="star-o"
      >
        收藏
      </van-button>
      <van-button
        type="primary"
        size="large"
        @click="onConsultDoctor"
        icon="chat-o"
      >
        问医生
      </van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getDiseaseDetail, searchDisease } from '@/services/disease'
import { showToast } from 'vant'
import dayjs from 'dayjs'
import type { Disease } from '@/types/disease'

const route = useRoute()
const router = useRouter()
const loading = ref(true)
const disease = ref<Disease>()
const searchKeyword = ref('')
const searchResults = ref<any[]>([])
const isSearching = ref(false)

const loadDiseaseDetail = async () => {
  try {
    const res = await getDiseaseDetail(route.params.id as string)
    if (res.data) {
      disease.value = res.data
    } else {
      showToast('获取疾病信息失败')
    }
  } catch (e) {
    showToast('获取疾病信息失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadDiseaseDetail()
})

// 搜索疾病
const onSearch = async () => {
  if (!searchKeyword.value.trim()) {
    showToast('请输入搜索关键词')
    return
  }

  try {
    isSearching.value = true
    const res = await searchDisease(searchKeyword.value.trim())

    if (res.data && res.data.success && res.data.data) {
      // 处理搜索结果，添加高亮匹配内容
      searchResults.value = res.data.data.map((item: any) => ({
        ...item,
        matchedContent: highlightMatchedContent(
          item,
          searchKeyword.value.trim()
        )
      }))

      if (searchResults.value.length === 0) {
        showToast('未找到相关疾病信息')
      }
    } else {
      searchResults.value = []
      showToast('搜索失败，请重试')
    }
  } catch (e) {
    console.error('搜索失败:', e)
    showToast('搜索失败，请重试')
    searchResults.value = []
  } finally {
    isSearching.value = false
  }
}

// 清除搜索
const onClearSearch = () => {
  searchKeyword.value = ''
  searchResults.value = []
}

// 清除搜索结果
const clearSearchResults = () => {
  searchResults.value = []
  searchKeyword.value = ''
}

// 跳转到疾病详情
const goToDisease = (diseaseId: number) => {
  if (diseaseId !== Number(route.params.id)) {
    router.push(`/disease/${diseaseId}`)
  } else {
    // 如果是当前疾病，清除搜索结果
    clearSearchResults()
  }
}

// 高亮匹配的内容
const highlightMatchedContent = (item: any, keyword: string) => {
  const fields = [
    'name',
    'summary',
    'symptoms',
    'causes',
    'treatment',
    'prevention',
    'medical_advice',
    'daily_care'
  ]
  const matches: string[] = []

  fields.forEach((field) => {
    if (item[field] && typeof item[field] === 'string') {
      const content = item[field].toLowerCase()
      const searchTerm = keyword.toLowerCase()

      if (content.includes(searchTerm)) {
        // 提取匹配部分及其上下文
        const index = content.indexOf(searchTerm)
        const start = Math.max(0, index - 20)
        const end = Math.min(content.length, index + searchTerm.length + 20)

        let excerpt = item[field].substring(start, end)
        if (start > 0) excerpt = '...' + excerpt
        if (end < content.length) excerpt = excerpt + '...'

        // 高亮关键词
        const regex = new RegExp(`(${keyword})`, 'gi')
        excerpt = excerpt.replace(regex, '<mark>$1</mark>')

        matches.push(`<strong>${getFieldName(field)}:</strong> ${excerpt}`)
      }
    }
  })

  return matches.slice(0, 2).join(' | ') // 最多显示2个匹配字段
}

// 获取字段中文名
const getFieldName = (field: string) => {
  const fieldNames: Record<string, string> = {
    name: '疾病名称',
    summary: '疾病概述',
    symptoms: '症状表现',
    causes: '病因分析',
    treatment: '治疗方法',
    prevention: '预防措施',
    medical_advice: '医疗建议',
    daily_care: '日常护理'
  }
  return fieldNames[field] || field
}

const onShare = () => {
  // TODO: 实现分享功能
  showToast('分享功能开发中')
}

const onFindDoctor = () => {
  // 跳转到医生列表，如果疾病有关联科室，则自动选择第一个科室
  const departmentId = disease.value?.departments?.[0]?.id
  if (departmentId) {
    router.push(
      `/consult/DoctorList?departmentId=${departmentId}&keyword=${disease.value?.name}`
    )
  } else {
    router.push(`/consult/DoctorList?keyword=${disease.value?.name}`)
  }
}

const onDepartmentClick = (dept: any) => {
  // 点击科室标签，跳转到医生列表并选择该科室
  router.push(
    `/consult/DoctorList?departmentId=${dept.id}&keyword=${disease.value?.name}`
  )
}

const onAddToFavorites = () => {
  // TODO: 实现收藏功能
  showToast('收藏功能开发中')
}

const onConsultDoctor = () => {
  // 跳转到医生列表，优先选择相关科室
  const departmentId = disease.value?.departments?.[0]?.id
  if (departmentId) {
    router.push(
      `/consult/DoctorList?departmentId=${departmentId}&keyword=${disease.value?.name}`
    )
  } else {
    router.push('/consult/DoctorList')
  }
}

// 获取疾病图片
const getDiseaseImage = (imageName?: string) => {
  if (imageName) {
    return `${import.meta.env.VITE_APP_API_BASE_URL}/public/images/${imageName}`
  }
  return '/src/assets/ad.png' // 默认图片
}

// 图片加载失败处理
const onImageError = (event: Event) => {
  const target = event.target as HTMLImageElement
  target.src = '/src/assets/ad.png'
}

// 格式化日期
const formatDate = (dateString: string) => {
  return dayjs(dateString).format('YYYY-MM-DD')
}
</script>

<style lang="scss" scoped>
.disease-page {
  padding-bottom: 60px;
  padding-top: 46px; /* 为导航栏留出空间，避免遮挡 */
  min-height: 100vh;
  background-color: var(--cp-bg);
}

.search-section {
  background: #fff;
  padding: 0 15px 10px;
  border-bottom: 1px solid #f5f5f5;

  :deep(.van-search) {
    padding: 10px 0;
    background: transparent;
  }

  :deep(.van-search__action) {
    color: #16c2a3;
    font-weight: 500;
  }
}

.search-results {
  background: #fff;
  margin: 10px 15px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .result-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background: linear-gradient(135deg, #16c2a3, #13b394);
    color: #fff;
    font-size: 14px;
    font-weight: 500;
  }

  .result-item {
    padding: 15px;
    border-bottom: 1px solid #f5f5f5;
    cursor: pointer;
    transition: background-color 0.3s ease;

    &:hover {
      background-color: #f8f9fa;
    }

    &:last-child {
      border-bottom: none;
    }

    .result-name {
      font-size: 16px;
      font-weight: bold;
      color: #121826;
      margin-bottom: 8px;
    }

    .result-summary {
      font-size: 14px;
      color: #666;
      margin-bottom: 8px;
      line-height: 1.5;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }

    .result-highlight {
      font-size: 12px;
      color: #999;
      line-height: 1.4;

      .label {
        color: #16c2a3;
        font-weight: 500;
        margin-right: 4px;
      }

      :deep(mark) {
        background: linear-gradient(135deg, #ffe066, #ffeb3b);
        color: #333;
        padding: 1px 3px;
        border-radius: 2px;
        font-weight: 500;
      }

      :deep(strong) {
        color: #16c2a3;
        font-weight: 500;
      }
    }
  }
}

.disease-detail {
  .disease-header {
    padding: 20px 15px;
    background-color: #fff;
    border-radius: 0 0 12px 12px;
    margin-bottom: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .disease-info {
      display: flex;
      align-items: flex-start;

      .disease-image {
        width: 80px;
        height: 80px;
        border-radius: 12px;
        margin-right: 15px;
        object-fit: cover;
        background-color: #f5f5f5;
        flex-shrink: 0;
      }

      .info-content {
        flex: 1;
        min-width: 0;

        .disease-name {
          font-size: 20px;
          font-weight: bold;
          margin: 0 0 8px 0;
          color: #121826;
        }

        .english-name {
          font-size: 14px;
          color: #6f6f6f;
          font-style: italic;
          margin: 0 0 10px 0;
        }

        .tags {
          display: flex;
          align-items: center;
          gap: 8px;
          flex-wrap: wrap;

          .special-tag {
            background: linear-gradient(135deg, #ff6b35, #f7931e);
            color: #fff;
            font-size: 12px;
            padding: 4px 8px;
            border-radius: 12px;
            white-space: nowrap;
          }

          .department-tag {
            background: linear-gradient(135deg, #16c2a3, #13b394);
            color: #fff;
            font-size: 12px;
            padding: 4px 8px;
            border-radius: 12px;
            white-space: nowrap;
            margin-left: 4px;
            cursor: pointer;
            transition: all 0.3s ease;

            &:hover {
              transform: translateY(-1px);
              box-shadow: 0 2px 8px rgba(22, 194, 163, 0.3);
            }

            &:active {
              transform: translateY(0);
            }
          }

          .update-time {
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
  }

  .detail-card {
    margin: 10px 15px;
    padding: 20px;
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

    h3 {
      font-size: 16px;
      font-weight: bold;
      margin: 0 0 15px;
      color: #121826;
      position: relative;
      padding-left: 12px;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 16px;
        background: linear-gradient(135deg, #16c2a3, #13b394);
        border-radius: 2px;
      }
    }

    .content-with-icon {
      display: flex;
      align-items: flex-start;
      gap: 10px;

      .section-icon {
        color: #16c2a3;
        font-size: 16px;
        margin-top: 2px;
        flex-shrink: 0;
      }

      p {
        margin: 0;
        flex: 1;
      }
    }

    p {
      color: var(--cp-text2);
      font-size: 14px;
      line-height: 1.6;
      margin: 0;
      text-align: justify;
    }

    .doctor-recommend {
      text-align: center;
      padding: 10px 0;
    }
  }
}

.bottom-actions {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  display: flex;
  gap: 10px;
  padding: 10px 15px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);

  .van-button {
    flex: 1;
    height: 44px;
    font-size: 16px;
    border-radius: 22px;

    &:first-child {
      background-color: #f7f8fa;
      color: #646566;
      border: 1px solid #ebedf0;
    }
  }
}

/* 修复导航栏遮挡问题 */
:deep(.van-nav-bar) {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background-color: #fff;
}

.loading {
  padding: 20px 15px;
}
</style>
